package com.company.site.user;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;

import com.company.base.interceptor.AuthInterceptor;
import com.company.base.utils.CheckUtil;
import com.company.base.utils.MD5Util;
import com.company.base.utils.WeChatUtil;
import com.company.site.mode.wechatuser.OnlineUser;
import com.company.site.mode.wechatuser.Sms;
import com.company.site.mode.wechatuser.WechatUser;

@Service
public class UserService {
	public static final String REGISTER_KEY="bycodecsga";
	
	@Resource
	UserMapper userMapper;
	/**
	 * 用户登录
	 * @param username
	 * @param password
	 * @return
	 */
	public WechatUser login(String username,String password){
		WechatUser user=new WechatUser();
		user.setUsername(username);
		user.setPassword(MD5Util.MD5(password+REGISTER_KEY));
		// 是否是志愿者   0：初始状态    1：审核中 2：审核成功 -1：审核不通过
		/*user.setIsVolunteer(1);*/
		// 初始时间为0
		/*user.setTotalTime(0);*/
		// 所在组织为0(无组织)
		/*user.setOrganid(0);*/
		return userMapper.userLogin(user);
	}
	
	/**
	 * 用户注册-添加用户
	 * @param user
	 * @return 返回添加成功后user-id
	 */
	public Long doRegister(WechatUser user){
		user.setPassword(MD5Util.MD5(user.getPassword()+REGISTER_KEY));
		userMapper.userRegiste(user);
		return user.getId();
	}

	/**
	 * 用户更新个人中心基本信息
	 * @param user
	 */
	public void updateUserInfo(WechatUser user){
		userMapper.updateUserInfo(user);
	}
	
	/**
	 * 根据用户id获取用户信息
	 * @param id
	 * @return
	 */
	public WechatUser getUserInfoById(long id){
		return userMapper.getUserInfoById(id);
	}
	
	/**
	 * 根据用户id获取用户信息
	 * @param id
	 * @return
	 */
	public WechatUser getUserInfoByUsername(String username){
		return userMapper.getUserInfoByUsername(username);
	}
	
	/**
	 * 检测用户修改密码时，提交的密码是否正确
	 * 如果通过，则修改密码
	 * @param id
	 * @param oldPwd
	 * @return
	 */
	public boolean checkUserPwd(long id,String oldPwd,String newPwd){
		oldPwd=MD5Util.MD5(oldPwd+REGISTER_KEY);
		WechatUser user=userMapper.getUserInfoById(id);
		if(user!=null && !CheckUtil.isEmpty(user.getPassword()) && user.getPassword().equals(oldPwd)){
			newPwd=MD5Util.MD5(newPwd+REGISTER_KEY);
			user.setId(id);
			user.setPassword(newPwd);
			userMapper.modifyPwd(user);
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 根据用户Id取得参与活动的总时间(审核通过的活动)
	 * @param id
	 * @return
	 */
	public long getPersonTime(long id){
		return userMapper.getPersonTime(id);
	}
	

	// 判断手机是否已注册
	public boolean getMobileInfo(String mobile) {
		long num = userMapper.getMobileInfo(mobile);
		if(num > 0){
			return true;
		}
		return false;
	}

	// 当前手机发送的验证码次数
	public Long getMobileCount(String mobile) {
		return userMapper.getMobileCount(mobile);
	}

	// 将发送验证码的数据保存到数据库
	public void sendCode(Sms sms) {
		userMapper.sendCode(sms);
	}

	// 验证码正确性及时效性
	public boolean checkNum(String mobile, String identityCode) {
		Sms sms = new Sms();
		sms.setMobile(mobile);
		sms.setChecknum(identityCode);
		long num = userMapper.checkNum(mobile,identityCode);
		if(num == 1){
			return true;
		}
		return false;
	}

	// 根据手机号码更新密码
	public void changePassword(String mobile, String password) {
		WechatUser user=new WechatUser();
		user.setMobile(mobile);
		user.setPassword(MD5Util.MD5(password+REGISTER_KEY));
		userMapper.changePassword(user);
	}

	// 根据组织Id找到组织名称
	public String getOrganization(long id) {
		return userMapper.getOrganization(id);
	}

	
	// 根据openId更新wechatUser
	public void updateWechatuserByOpenid(WechatUser wechatUser){
		 userMapper.updateWechatuserByOpenid(wechatUser);
	};
	// 根据openId删除wechatUser
	public void deleteWechatuserByOpenid(WechatUser wechatUser){
		userMapper.deleteWechatuserByOpenid(wechatUser);
	};
	// 根据userName更新wechatUser
	public void updateWechatuserByUsername(WechatUser wechatUser){
		 userMapper.updateWechatuserByUsername(wechatUser);
	};

	
	/**
	 * 根据微信用户openid获取用户信息
	 * @param openid
	 * @return
	 */
	public  WechatUser getUserInfoByOpenid(String openid){
		return userMapper.getUserInfoByOpenid(openid);
	}
	
	/**
	 *  用户关注公众号后，从微信服务器取得用户的基本信息
	 * @param openID
	 * @throws UnsupportedEncodingException 
	 */
	public synchronized void subscribeUser(String openID,HttpServletRequest request) throws UnsupportedEncodingException{
		WechatUser w=getUserInfoByOpenid(openID);
		WechatUser user=WeChatUtil.getUserInfo(openID);
		if(w==null){
//			if(!CheckUtil.isEmpty(user)&&!CheckUtil.isEmpty(user.getHeadimgurl())){
//				user.setHeadimgurl(user.getHeadimgurl().replace("/0", "/132"));	
//			}
			user.setIsRegister(0);
			user.setOpenid(openID);
//			user.setNickname(URLEncoder.encode(user.getNickname(), "UTF-8"));
			userMapper.addUser(user);
		}else {
			if(w.getSubscribe().equals(0)&&user.getSubscribe().equals(1)){
				w.setSubscribe(1);
				userMapper.updateUserInfo(w);
				HttpSession session=request.getSession();
				OnlineUser onlineUser = new OnlineUser();
				onlineUser.setUserInfo(w);
				session.setAttribute(AuthInterceptor.OPERATOR, onlineUser);
			}
		}
		
	}

	/**
	 *  用户关注公众号后，从微信服务器取得用户的基本信息
	 * @param openID
	 * @throws UnsupportedEncodingException 
	 */
	public void unsubscribeUser(String openID,HttpServletRequest request) throws UnsupportedEncodingException{
		WechatUser w=getUserInfoByOpenid(openID);
//		WechatUser user=WeChatUtil.getUserInfo(openID);
//		if(w==null){
////			if(!CheckUtil.isEmpty(user)&&!CheckUtil.isEmpty(user.getHeadimgurl())){
////				user.setHeadimgurl(user.getHeadimgurl().replace("/0", "/132"));	
////			}
//			user.setIsRegister(0);
//			user.setOpenid(openID);
////			user.setNickname(URLEncoder.encode(user.getNickname(), "UTF-8"));
//			userMapper.addUser(user);
//		}else {
		//	if(w.getSubscribe().equals(0)&&user.getSubscribe().equals(1)){
				w.setSubscribe(0);
				userMapper.updateUserInfo(w);
				HttpSession session=request.getSession();
				OnlineUser onlineUser = new OnlineUser();
				onlineUser.setUserInfo(w);
				session.setAttribute(AuthInterceptor.OPERATOR, onlineUser);
		//	}
		//}
		
	}
	public void addWechatUser(WechatUser wechatUser) {
		userMapper.addWechatUser(wechatUser);
	}

	public void updateVoteWechatuser(WechatUser wechatUser) {
		userMapper.updateVoteWechatuser(wechatUser);
	}

}
